/**
 * 宽带预约列表
 */
(function($) {
  var pageData = {};
  var pageCount = 1;
  var filterType = 3;
  var pageNumber = 0;
  var custPageNumber = 0;
  var groupList = new Array();
  var custList = new Array();
  /*
  封装参数
  */
  var getMyParams = function(id) {
    var params = "?";
    var myParam = getParams();
    if (myParam) {
      params += myParam;
      if (id) {
        params += "&";
      }
    }
    if (id) {
      params += "id=" + id;
    }

    return params;
  };

  var bind = function(object, clickFunc) {
    itemOnClick(object, clickFunc);
  }

  var itemOnClick = function(object, clickFunc) {
    $(object).off("click"); //取消li事件
    /*li事件*/
    $(object).on("click", function() {
      var $siblingsNode = $(this).siblings();
      var primaryClass = "select-item";
      var defaultColor = "#fff";
      var selectColor = "#0c79b1";

      if ($siblingsNode.hasClass(primaryClass)) {
        $siblingsNode.removeClass(primaryClass);
        $siblingsNode.css("background-color", defaultColor);
      }
      if ($(this).hasClass(primaryClass)) {
        $(this).removeClass(primaryClass);
        $(this).css("background-color", defaultColor);
      } else {
        $(this).addClass(primaryClass);
        $(this).css("background-color", selectColor);
      }
      clickFunc(this);
      event.stopPropagation();
    });
  }

  var showCustMember = function(data) {
    console.log("showCustMember");
    var unreadCount = 0;
    var readCount = 0;

    if (data.rtnCode != 1000) {
      alert(data.rtnMsg);
      return;
    }
    var list = data.return.custMemberList;
    console.log("list.length=" + list.length);
    if (list.length == 0) {
      custPageNumber--;
      console.log("custPageNumber=" + custPageNumber);
    }

    for (var i = 0; i < list.length; i++) {
      list[i].memberNameEx = list[i].memberName + list[i].officalName + ":" + list[i].productNo;
      console.log("list[i].custMemberId=" + list[i].custMemberId);
      console.log("list[i].memberNameEx=" + list[i].memberNameEx);
      custList.push(list[i]);
    }
    var $cust_list = $('#amz-cust-list');
    var source = $cust_list.text();
    var template = Handlebars.compile(source);
    var data = {
      custlist: custList,
      "error": "获取集团联系人为空请重试"
    };
    $("#cust-list").children('li').remove();
    $("#cust-list").children('div').remove();
    var html = template(data);
    $cust_list.before(html);
    bind("#cust-list > li", custClickFunc);
    $("#cust_contactor").attr("placeholder", "请选择集团联系人");
  }



  /*
  加载数据
  */
  var callSaveTaskLog = function(data) {
    $('#modal').modal('open');
    console.log("data=" + data);
    $.ajax({
      type: "post",
      contentType: "application/json",
      url: Constants.rpcEsopHost + "addWorkNote",
      data: data,
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        $('#modal').modal('close');
        pageData = data;
        console.info(data);
        window.location.href = "tasklog_list.html" + "?" + getParams();
      },
      error: function(textStatus) {
        $('#modal').modal('close');
        alert("添加任务日志失败！" + textStatus);
        console.info("request error:" + textStatus);
      }
    });
  };

  var loadCustMember = function(custPageNumber, groupId) {
    showLoadingBar($("#loadingCust"), true);
    $("#cust_contactor").attr("placeholder", "正在获取集团联系人...");
    var empCode = getParamValue("empCode");
    var data = JSON.stringify(getCustMemberJsonParams(getParamValue("token"), empCode, groupId, custPageNumber, 50));
    console.log("data=" + data);
    $.ajax({
      type: "post",
      contentType: "application/json",
      url: Constants.rpcEsopHost + "qryCustMember",
      data: data,
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        showLoadingBar($("#loadingCust"), false);
        pageData = data;
        console.info(data);
        showCustMember(data);
      },
      error: function(textStatus) {
        showLoadingBar($("#loadingCust"), false);
        alert("获取集团联系人失败！");
        console.info("request error:" + textStatus);
      }
    });
  };

  /*
  显示数据
  */
  var showGroupData = function(data) {
    if (data.groupInfoList instanceof Array) {
      list = data.groupInfoList;
      for (var i = 0; i < list.length; i++) {
        groupList.push(list[i]);
      }
    } else if (data.groupInfoList instanceof Object) {
      if(data.groupInfoList.empty == undefined){
        groupList.push(data.groupInfoList);
      }
    }
    var $tpl = $('#amz-group-list');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var myData = {
      list: groupList,
      "error": "没有集团信息"
    };

    $("#group-list").children('li').remove();
    $("#group-list").children('div').remove();

    var html = template(myData);
    $tpl.before(html);
    bind("#group-list > li", groupClickFunc);
  };

  var groupClickFunc = function(object) {
    var groupID = $(object).find("input[name='group_id']").val();
    var groupName = $(object).find("div[name='group_name']").html();
    $("#group_id").val(groupID);
    $("#group_name").val(groupName);
    $('#my-alert').modal('close');
    custList = [];
    $("#cust-list").children('li').remove();
    $("#cust-list").children('div').remove();
    loadCustMember(custPageNumber, groupID);
  }

  var custClickFunc = function(object) {
    var cust_name = $(object).find("input[name='cust_name']").val();
    var cust_name_ex = $(object).find("div[name='cust_name_ex']").html();
    $("#cust_contactor").val(cust_name);
    $('#my-alert-cust').modal('close');
  }

  var loadGroupData = function(firstPage) {
    showLoadingBar($("#loadingGroup"), true);
    var keyword = $("#group_keyword").val();
    params = buildQueryGroupParams(firstPage, keyword);

    $.ajax({
      type: "post",
      contentType: "application/json",
      data: JSON.stringify(params),
      url: Constants.rpcEsopHost + "queryGrouInfo",
      dataType: "json",
      async: true,
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        showLoadingBar($("#loadingGroup"), false);
        console.log("data = " + data);
        pageData = data.return;
        console.info(data.return);
        if (data.rtnCode != 1000) {
          // showBottomMsg(data.rtnMsg);
          console.log("获取RPC接口返回失败！code:" + data.rtnCode);
          return;
        }
        if (data.return.resultCode != "00") {
          // showBottomMsg(data.return.resultDesc);
          console.log("获取信息接口返回失败！code:" + data.return.resultCode);
          return;
        }
        showGroupData(data.return);
      },
      error: function(textStatus) {
        showLoadingBar($('#loadingGroup'), false);;
        showBottomMsg("获取信息失败！");
        console.info("request error:");
      }
    });
  };

  var buildQueryGroupParams = function(pageNumber, keyword) {
    var url = "grpName=";
    if (isDigital(keyword)) {
      url = url + "&grpNo=" + keyword + "&serviceNo=&pageStart=" + pageNumber*30 + "&pageLimit=30";
    } else {
      url = url + encodeURI(keyword) + "&grpNo=" + "&serviceNo=&pageStart=" + pageNumber*30 + "&pageLimit=30";
    }

    params = {
      "token": getParamValue("token"),
      "staffNo": getParamValue("EmpCode"),
      "passUrl": url
    };
    console.log("request:" + JSON.stringify(params));
    return params;
  }

  var isDigital = function(keyword) {
    var reg = /^[0-9]*$/;
    if (reg.test(keyword)) {
      return true;
    }
    return false;
  }

  var invalidParam = function(val, errorMsg) {
    console.log("val=" + val + ",msg=" + errorMsg);
    if (val) {
      return false;
    } else {
      alert(errorMsg);
      return true;
    }
  }

  var invalidEndDate = function(start, end) {
    startDate = new Date(start);
    endDate = new Date(end);
    if (endDate < startDate) {
      alert("结束时间不能小于开始时间,请重新选择");
      return true;
    } else {
      return false;
    }
  }

  var saveTaskLog = function() {
    var title = $("#title").val();
    if (invalidParam(title, "请输入日志标题")) {
      return;
    }
    title = encodeURIComponent(title);
    var start = $("#start").val();
    if (invalidParam(start, "请选择创建时间")) {
      return;
    }
    start = encodeURIComponent(start + " 00:00:00");
    var end = $("#end").val();
    if (invalidParam(end, "请选择结束时间")) {
      return;
    }
    end = encodeURIComponent(end + " 23:59:59");
    if (invalidEndDate($("#start").val(), $("#end").val())) {
      return;
    }   
    var chiefmgrflag = $('input[name="chiefmgrflagRadio"]:checked').val();
    var content = $("#content").val();
    if (invalidParam(content, "请输入日志内容")) {
      return;
    }
    content = encodeURIComponent(content);
    var actionKind = $("#actionKind").val();
    if (invalidParam(actionKind, "请选择办理事宜")) {
      return;
    }
    var guanhuaiType = $("#guanhuaiType").val();
    if (actionKind == 3) {
      if (invalidParam(guanhuaiType, "请选择服务关怀事项")) {
        return;
      }
    } else {
      guanhuaiType = "";
    }
    var group_name = $("#group_name").val();
    var group_id = $("#group_id").val();
    if (invalidParam(group_name, "请选择集团客户")) {
      return;
    }
    group_name = encodeURIComponent(group_name);
    var actionType = $("#actionType").val();
    if (invalidParam(actionType, "请选择工作方式")) {
      return;
    }
    var cust_contactor = $("#cust_contactor").val();
    // if(invalidParam(cust_contactor, "请选择集团联系人")){
    //   return;
    // }

    var empCode = getParamValue("empCode");
    var data = JSON.stringify(getAddTaskLogJsonParams(getParamValue("token"), empCode, actionType, actionKind, content, title, start, end, group_id, group_name, chiefmgrflag, guanhuaiType, cust_contactor));
    callSaveTaskLog(data);
  }

  $(function() {
    /*滚动条*/
    var $doc = $("#group-list-div");
    $doc.scroll(function() {
      scrollHeight = $(this)[0].scrollHeight;
      height = $doc.height();
      scorollTop = Math.ceil($doc.scrollTop());
      console.log("height = " + height);
      console.log("scorollTop = " + scorollTop);
      console.log("scrollTop = " + scorollTop);
      console.log("sub:" + (scrollHeight - height - scorollTop));
      if ((scrollHeight - height - scorollTop) <= 30) {
        var $msg = $("#no-data-msg");
        console.log("debug 1");
        if (!$.isEmptyObject(pageData)) {
          console.log("debug 2");
          if (!$msg.hasClass("am-hide")) {
            console.log("debug 3");
            $msg.addClass("am-hide");
          }
          console.log("pageNumber=" + pageNumber);
          pageNumber++;
          loadGroupData(pageNumber);
        } else {
          console.log("debug 5");
          if ($msg.hasClass("am-hide")) {
            console.log("debug 6");
            $msg.removeClass("am-hide");
          }
        }
      }
    });

    $("#submit-btn").on("click", function() {
      saveTaskLog();
    });

    $("#query-group-btn").on("click", function() {
      console.log("click query group");
      groupList = [];
      loadGroupData(pageNumber);
    });

    $("#group_name").on("click", function() {
      $('#my-alert').modal('open');
    });
    $("#cust_contactor").on("click", function() {
      var group_name = $("#group_name").val();
      if (invalidParam(group_name, "请先选择集团客户")) {
        return;
      }
      $('#my-alert-cust').modal('open');
    });

    $("#actionKind").on('change', function() {
      if ($(this).val() == 3) {
        $("#guanhuaiTr").show();
      } else {
        $("#guanhuaiTr").hide();
      }
    });
  });
})(jQuery);